﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShardMath
{
    public class Parsers
    {
        static int postfix(tokenObject[] tokens)
        {
            stackObject stack = new stackObject(tokens.Length);
            int position = -1;
            while (position < (tokens.Length - 1))
            {
                position = position + 1;
                tokenObject token = tokens[position];
                if (token.isOperand())
                {
                    //token is operand
                    stack.push(token.getOperand());
                }
                else
                {
                    string[] allowed = new string[5] { "+", "-", "*", "/", "^" };
                    //token is operator
                    if (allowed.Contains(token.getOperator()))
                    {
                        int Op2 = (int)stack.pop();
                        int Op1 = (int)stack.pop();
                        int result = 0;
                        switch (token.getOperator())
                        {
                            case "+":
                                result = Op1 + Op2;
                                break;
                            case "-":
                                result = Op1 - Op2;
                                break;
                            case "/":
                                result = Op1 / Op2;
                                break;
                            case "*":
                                result = Op1 * Op2;
                                break;
                            case "^":
                                if (Op2 < 1)
                                {
                                    result = 1;
                                }
                                else
                                {
                                    result = Op1;
                                    for (int i = 1; i <= (Op2 - 1); i++)
                                    {
                                        result = result * 2;
                                    }
                                }
                                break;
                        }
                        stack.push(result);
                    }
                    else
                    {
                        Console.WriteLine("Garbage Token: " + token.getOperator());
                    }
                }
            }
            return (int)stack.pop();
        }
    }
}
    